package com.appspot.modutajataja;

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.appspot.domain.GameVO;

public class GameActivity extends Activity {
	TextView[] text_score = new TextView[3];
	ImageView[] img_life = new ImageView[7];
	ImageView life_touch;
	ImageView life_moa;
	ImageView life_crash;
	ImageButton touch_game;
	ImageButton moa_game;
	ImageButton crash_game;
	ImageButton homeback;
	
	private ProgressDialog pDialog;
	private Animation aniLifeAlpha;
	private String userId;
	
	GameVO game = new GameVO();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game);

		userId = getIntent().getStringExtra("userId");	
		
		new getGameInfo(this).execute();
		
		Context mContext = getApplicationContext();
		LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.game_select_dialog, (ViewGroup) findViewById(R.id.layout_root));

		AlertDialog.Builder aDialog = new AlertDialog.Builder(GameActivity.this);
		aDialog.setView(layout);
		aDialog.setNegativeButton(R.string.Click, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		AlertDialog dialog = aDialog.create();
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		dialog.show();

		TextView event_time = (TextView)findViewById(R.id.limitTime);
		Calendar now = Calendar.getInstance();
		event_time.setText("EVENT 종료 시간 : " + (23 - now.get(Calendar.HOUR_OF_DAY)) + "시간 " 
				+ (60 - now.get(Calendar.MINUTE)) + "분");
		
		touch_game = (ImageButton) findViewById(R.id.gs_btn1);
		touch_game.setOnClickListener(new GameHandler());
		moa_game = (ImageButton) findViewById(R.id.gs_btn2);
		moa_game.setOnClickListener(new GameHandler());
		crash_game = (ImageButton) findViewById(R.id.gs_btn3);
		crash_game.setOnClickListener(new GameHandler());
		
		aniLifeAlpha = new AlphaAnimation(1.0f, 0.0f);	
		aniLifeAlpha.setDuration(1000);
		aniLifeAlpha.setFillAfter(true);
		
		life_touch = (ImageView)findViewById(R.id.life_touch);
		life_touch.setScaleX(2.0f);
		life_touch.setScaleY(2.0f);
		life_moa = (ImageView)findViewById(R.id.life_moa);
		life_moa.setScaleX(2.0f);
		life_moa.setScaleY(2.0f);
		life_crash = (ImageView)findViewById(R.id.life_crash);		
		life_crash.setScaleX(2.0f);
		life_crash.setScaleY(2.0f);

		for(int i=0; i<7; i++) {
			img_life[i] = (ImageView)findViewById(R.id.life1+i);
		}
		
		for(int i=0; i<3; i++) {
			text_score[i] = (TextView) findViewById(R.id.score1+i);
			text_score[i].setTypeface(Typeface.createFromAsset(getAssets(), "fonts/cartoonist.ttf"));
		}
		pDialog.dismiss();
	}
	
	class GameHandler implements OnClickListener {
		Handler handler = new Handler();

		@Override
		public void onClick(View v) {
			img_life[game.getGameLife()-1].setImageResource(R.drawable.life_kill);
			
			touch_game.setEnabled(false);
			moa_game.setEnabled(false);
			crash_game.setEnabled(false);
			handler.postDelayed(new splashhandler(), 1000);

			if (v.getId() == R.id.gs_btn1) {
				life_touch.setVisibility(View.VISIBLE);
				life_touch.setAnimation(aniLifeAlpha);
				life_touch.startAnimation(aniLifeAlpha);				
				handler.postDelayed(new Runnable() {
					public void run() {
						startActivity(new Intent(GameActivity.this, TouchGame.class).putExtra("userId", userId));
						finish();
					}
				}, 1000);
			} else if (v.getId() == R.id.gs_btn2) {
				life_moa.setVisibility(View.VISIBLE);
				life_moa.setAnimation(aniLifeAlpha);
				life_moa.startAnimation(aniLifeAlpha);
				handler.postDelayed(new Runnable() {
					public void run() {
						startActivity(new Intent(GameActivity.this, MoaGame.class).putExtra("userId", userId));
						finish();	
					}
				}, 1000);				
			} else if (v.getId() == R.id.gs_btn3) {
				life_crash.setVisibility(View.VISIBLE);
				life_crash.setAnimation(aniLifeAlpha);
				life_crash.startAnimation(aniLifeAlpha);
				handler.postDelayed(new Runnable() {
					public void run() {
						startActivity(new Intent(GameActivity.this, CrashGame.class).putExtra("userId", userId));				
						finish();
					}
				}, 1000);
			}
		}

		class splashhandler implements Runnable {
			public void run() {
				touch_game.setEnabled(true);
				moa_game.setEnabled(true);
				crash_game.setEnabled(true);
			}
		}
	} // end of GameHandler Class
		
	class getGameInfo extends AsyncTask<Void, Void, Void> {
		Context mc;
		
		public getGameInfo(Context context) {
			this.mc = context;
			pDialog = new ProgressDialog(mc);
		}
		
		@Override
		protected void onPreExecute() {
			pDialog.setMessage("<GameScore LOADING>");
			pDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				HttpClient client = new DefaultHttpClient();
				HttpPost post = new HttpPost(C.getGameInfoURL);

				List<NameValuePair> gameScore = new ArrayList<NameValuePair>();
				gameScore.add(new BasicNameValuePair("userId", userId));
				
				post.setEntity(new UrlEncodedFormEntity(gameScore, HTTP.UTF_8));	
				HttpResponse response = client.execute(post);
				HttpEntity entity = response.getEntity();
				
				XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
				parser.setInput(new InputStreamReader(entity.getContent()));
				
				while (parser.next() != XmlPullParser.END_DOCUMENT) {
					String name = parser.getName();
					
					if( name!= null && name.equals("gameLife")) {
						game.setGameLife(Integer.parseInt(parser.nextText()));
					} else if( name!= null && name.equals("touchTime")) {						
						game.setTouchTime(Long.parseLong(parser.nextText()));
					} else if( name!= null && name.equals("moaTime")) {
						game.setMoaTime(Long.parseLong(parser.nextText()));
					} else 	if( name!= null && name.equals("crashTime")) {
						game.setCrashTime(Long.parseLong(parser.nextText()));
					}
				}				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			for (int i=0; i<game.getGameLife(); i++) {
				img_life[i].setImageResource(R.drawable.life);
			}
			
			long touch_time = game.getTouchTime();
			long moa_time = game.getMoaTime();
			long crash_time = game.getCrashTime();		
			text_score[0].setText(String.format("%02d : %02d : %02d", touch_time/1000/60, (touch_time/1000)%60, (touch_time%1000)/10));
			text_score[1].setText(String.format("%02d : %02d : %02d", moa_time/1000/60, (moa_time/1000)%60, (moa_time%1000)/10));
			text_score[2].setText(String.format("%02d : %02d : %02d", crash_time/1000/60, (crash_time/1000)%60, (crash_time%1000)/10));
		}
	}
	public void HomebackOnClick(View v) {
		startActivity(new Intent(GameActivity.this, MainActivity.class).putExtra("userId", userId));
		GameActivity.this.finish();
	}
	
	@Override
	public void onBackPressed() {

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage("게임을 종료 하시겠습니까?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								finish();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = alt_bld.create();
		alert.setTitle("게임 종료");
		alert.setIcon(R.drawable.ic_launcher);
		alert.show();
	}
};